import { createRouter, createWebHistory } from 'vue-router'
import { isAuthenticated } from '@/utils/auth'
import HomeView from '../views/HomeView.vue'
import TheaterCreate from '../views/TheaterCreate.vue'
import TheaterDetail from '../views/TheaterDetail.vue'
import Theater from '../views/Theater.vue'
import TheaterTwo from '../views/TheaterTwo.vue'
import ExcelConvert from '../views/ExcelConvert.vue'
import ImageGenerate from '../views/ImageGenerate.vue'
import Login from '../views/Login.vue'
import ce from '../views/ce.vue'
import TheaterList from '../views/TheaterList.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: { requiresAuth: false },
    },
    {
      path: '/z',
      name: 'ce',
      component: ce,
      meta: { requiresAuth: false },
    },
    {
      path: '/TheaterList',
      name: 'TheaterList',
      component: TheaterList,
      meta: { requiresAuth: false },
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta: { requiresAuth: false },
    },
    {
      path: '/ExcelConvert',
      name: 'ExcelConvert',
      component: ExcelConvert,
      meta: { requiresAuth: true, title: 'Excel转换' },
    },
    {
      path: '/theaterCreate',
      name: 'theaterCreate',
      component: TheaterCreate,
      meta: { requiresAuth: true, title: '创建影院' },
    },
    {
      path: '/TheaterDetail/:task_id?',
      name: 'TheaterDetail',
      component: TheaterDetail,
      meta: { requiresAuth: true, title: '影院详情' },
      props: true,
    },
    {
      path: '/Theater/:task_id?',
      name: 'Theater',
      component: Theater,
      meta: { requiresAuth: true, title: '影院管理' },
      props: true,
    },
     {
      path: '/TheaterTwo/:task_id?',
      name: 'TheaterTwo',
      component: TheaterTwo,
      meta: { requiresAuth: true, title: '影院管理' },
      props: true,
    },
    {
      path: '/ImageGenerate',
      name: 'ImageGenerate',
      component: ImageGenerate,
      meta: { requiresAuth: true, title: '图片生成' },
    },
  ],
})

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title as string
  }

  const requiresAuth = to.meta.requiresAuth !== false

  if (requiresAuth) {
    if (isAuthenticated()) {
      next()
    } else {
      console.log('用户未登录或 token 已过期，跳转到登录页')
      next({
        path: '/login',
        query: { redirect: to.fullPath },
      })
    }
  } else {
    if (to.path === '/login' && isAuthenticated()) {
      const redirect = to.query.redirect as string
      next(redirect || '/theaterCreate')
    } else {
      next()
    }
  }
})

router.afterEach((to, from) => {
  console.log(`路由跳转: ${from.path} -> ${to.path}`)
})

export default router
